package com.example.api.service.impl;

import com.example.api.mapper.DistributionMapper;
import com.example.api.mapper.DriverMapper;
import com.example.api.mapper.VehicleMapper;
import com.example.api.model.entity.Distribution;
import com.example.api.model.entity.Driver;
import com.example.api.model.entity.Sale;
import com.example.api.model.entity.Vehicle;
import com.example.api.service.DistributionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class DistributionServiceImpl implements DistributionService {

    @Resource
        private DistributionMapper distributionMapper;

    @Resource
    private DriverMapper driverMapper;

    @Resource
    private VehicleMapper vehicleMapper;

    @Override
    public Distribution save(Distribution distribution) throws Exception {
        // 如果是新记录，设置ID
        if (distribution.getId() == null || distribution.getId().isEmpty()) {
            distribution.setId(UUID.randomUUID().toString());
        }

        // 检查是否是新记录
        Distribution existingDistribution = distributionMapper.findById(distribution.getId());
        if (existingDistribution == null) {
            // 获取司机和车辆信息
            Driver driver = driverMapper.findById(distribution.getDid());
            Vehicle vehicle = vehicleMapper.findById(distribution.getVid());

            // 检查司机和车辆状态
            if (driver == null || vehicle == null) {
                throw new Exception("请求参数错误");
            }

            if (driver.isDriving() || vehicle.isDriving()) {
                throw new Exception("司机或货车状态不可用");
            }

            // 更新司机和车辆状态为正在驾驶
            driverMapper.updateDriving(true, distribution.getDid());
            vehicleMapper.updateDriving(true, distribution.getVid());
        }

        // 保存配送信息
        if (existingDistribution == null) {
            distributionMapper.insert(distribution);
        } else {
            distributionMapper.update(distribution);
        }

        return distribution;
    }

    @Override
    public List<Distribution> findAll() {
        return distributionMapper.findAll();
    }

    public void delete(String id) {
        distributionMapper.deleteById(id);
    }

    public List<Distribution> searchByCarnumber(String number) {
        return distributionMapper.findAllByCarnumberLike("%" + number + "%");
    }
}
